package com.alibaba.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.yygh.client.DictFeignClient;
import com.alibaba.yygh.enums.DictEnum;
import com.alibaba.yygh.hosp.repository.HospitalRepository;
import com.alibaba.yygh.hosp.service.HospitalService;
import com.alibaba.yygh.model.hosp.Department;
import com.alibaba.yygh.model.hosp.Hospital;
import com.alibaba.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description: HospitalServiceImpl
 * @author: gql
 * @date: 2021/11
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    /**
     * 注入HospitalRepository
     */
    @Autowired
    private HospitalRepository hospitalRepository;

    /**
     * 注入远程数据字典
     */
    @Autowired
    private DictFeignClient dictFeignClient;

    /**
     * 1.上传医院到MongoDB
     * 将医院信息添加到MongoDB中
     * 如果已经添加过,再次添加就是修改
     * @param paramMap
     */
    @Override
    public void saveHosp(Map<String, Object> paramMap) {
        // 1.使用fastjson将Map转换为JSON字符串再转换为对象
        Hospital hospital = JSONObject.parseObject(JSONObject.toJSONString(paramMap), Hospital.class);

        // 2.查询医院信息是否已经添加
        Hospital existHospital = hospitalRepository.findByHoscode(hospital.getHoscode());

        if (null != existHospital) {
            // 修改
            hospital.setId(existHospital.getId());
            hospital.setCreateTime(existHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setStatus(existHospital.getStatus());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        } else {
            //添加
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setStatus(0);
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 2.根据hoscode获取医院信息
     * @param hoscode
     * @return
     */
    @Override
    public Hospital getHospitalByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.findByHoscode(hoscode);
        return hospital;
    }

    /**
     * 3.1查询医院列表-带分页
     * @param page 当前页
     * @param limit 每页记录数
     * @param hospitalQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        // 1.设置排序规则
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

        // 2.设置分页数据
        Pageable pageable = PageRequest.of(page - 1, limit, sort);

        // 3.条件匹配器
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        // 4.将departmentQueryVo转换为department
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);

        // 5.封装查询条件
        Example<Hospital> example = Example.of(hospital, matcher);

        // 6.执行查询
        Page<Hospital> pages = this.hospitalRepository.findAll(example, pageable);

        // 7.遍历封装
        pages.getContent().stream().forEach(item -> {
            this.packageHosp(item);
        });
        return pages;
    }

    /**
     * 3.2封装编号对应的名称
     * @param item
     */
    private Hospital packageHosp(Hospital item) {
        /**
         * hostypeString医院等级、
         * provinceString省、
         * cityString市、
         * districtString区
         */
        String hostypeString = dictFeignClient.getName(DictEnum.HOSTYPE.getDictCode(), item.getHostype());
        String provinceString = dictFeignClient.getName(item.getProvinceCode());
        String cityString = dictFeignClient.getName(item.getCityCode());
        String districtString = dictFeignClient.getName(item.getDistrictCode());

        // 封装到Map集合
        item.getParam().put("hostypeString", hostypeString);
        item.getParam().put("fullAddress", provinceString + cityString + districtString + item.getAddress());
        return item;
    }

    /**
     * 4.查询医院详情
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(String id) {
        // 1.根据id得到Hospital对象
        Hospital hospital = hospitalRepository.findById(id).get();

        // 2.封装编号对应的名称
        hospital = this.packageHosp(hospital);

        // 3.创建返回结果集
        Map<String, Object> result = new HashMap<>();

        // 3.1添加医院基本信息（包含医院等级）
        result.put("hospital", hospital);

        // 3.2添加预约规则bookingRule
        result.put("bookingRule", hospital.getBookingRule());

        // 4. 医院基本信息不需要预约规则
        hospital.setBookingRule(null);

        return result;
    }

    /**
     * 2.根据医院名称获取医院列表
     * @param hosname
     * @return
     */
    @Override
    public List<Hospital> findByHosname(String hosname) {
        return this.hospitalRepository.findByHosnameLike(hosname);
    }

    /**
     * 4.获取医院预约挂号详情
     * @param hoscode
     * @return
     */
    @Override
    public Map<String, Object> getHospDetail(String hoscode) {
        // 1.获取医院信息
        Hospital hospital = this.packageHosp(this.getHospitalByHoscode(hoscode));
        // 2.封装返回
        Map<String, Object> result = new HashMap<>();
        // 医院详情
        result.put("hospital", hospital);
        // 预约规则
        result.put("bookingRule", hospital.getBookingRule());
        // 不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }
}
